package cn.dongjak.example.spring.security.config;

import cn.dongjak.example.spring.security.apitoken.ResultExceptionTranslationFilter;
import cn.dongjak.example.spring.security.apitoken.TokenAuthenticationFilter;
import cn.dongjak.example.spring.security.apitoken.TokenAuthenticationProvider;
import cn.dongjak.example.spring.security.apitoken.TokenService;
import cn.dongjak.example.spring.security.vo.ApiResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.ExceptionTranslationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
@Profile("default")
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final TokenService tokenService;
    private final DataSource dataSource;
    private final CustomAccessDeniedHandler accessDeniedHandler;
    private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    public SecurityConfiguration(TokenService tokenService,
                                 DataSource dataSource,
                                 CustomAccessDeniedHandler accessDeniedHandler,
                                 RestAuthenticationEntryPoint restAuthenticationEntryPoint) {
        this.tokenService = tokenService;
        this.dataSource = dataSource;
        this.accessDeniedHandler = accessDeniedHandler;
        this.restAuthenticationEntryPoint = restAuthenticationEntryPoint;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth
                .authenticationProvider(new TokenAuthenticationProvider(tokenService))
                .jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username,password,enabled from example_user where username=?")
                .authoritiesByUsernameQuery("select username,name "
                        + "from sys_role "
                        + "where username = ?")
                .and()
                .inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder())
                .withUser("dongjak")
                .password(new BCryptPasswordEncoder().encode("123394"))
                .roles("USER")
                .and()
                .withUser("admin")
                .password(new BCryptPasswordEncoder().encode("123394"))
                .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .addFilterAfter(new TokenAuthenticationFilter(),
                        BasicAuthenticationFilter.class)
                .addFilterAfter(new ResultExceptionTranslationFilter(),
                        ExceptionTranslationFilter.class)
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                //region 启用http basic认证
               /* .and()
                .httpBasic()
                .authenticationEntryPoint(customBasicAuthenticationEntryPoint())*/
                //endregion
        ;
    }


    @Bean
    public BasicAuthenticationEntryPoint customBasicAuthenticationEntryPoint() {
        return new BasicAuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException
                    authEx) throws IOException {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.setHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
                response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                PrintWriter writer = response.getWriter();
                writer.println(ApiResponse.builder()
                        .code(HttpServletResponse.SC_UNAUTHORIZED)
                        .message(authEx.getMessage())
                        .build().toJsonString());
            }

            @Override
            public void afterPropertiesSet() throws Exception {
                setRealmName("AAA");
                super.afterPropertiesSet();
            }
        };
    }
}